package com.uenpay.im.ui.old.activity.group;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Handler.Callback;
import android.os.Message;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.qiyunxin.android.http.HttpInvokeResultCode;
import com.qyx.android.entity.GroupTalkEntity;
import com.qyx.android.message.type.PacketType;
import com.qyx.android.protocol.SessionModel;
import com.uenpay.im.IMApplication;
import com.uenpay.im.R;
import com.uenpay.im.ui.old.activity.chat.ChatActivity;
import com.uenpay.im.ui.old.activity.pwd.SetPayPwdActivity;
import com.uenpay.im.ui.old.activity.wallet.ChargeActivity;
import com.uenpay.im.ui.old.activity.wallet.WalletHandle;
import com.uenpay.im.callback.IOnBottomDialogListener;
import com.uenpay.im.configuration.APIConfiguration;
import com.uenpay.im.invokeitems.GetGroupMessageDetail;
import com.uenpay.im.weight.DialogUtility;
import com.uenpay.im.weight.PayPwdDialog;
import com.uenpay.im.weight.RoundImageView;
import com.uenpay.util.app.base.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.MessageFormat;

/**
 * @author SL
 * @version 1.0
 * @copyRight http://www.qiyunxin.com
 * @E-mail:
 * @date 创建时间：2016-5-9 下午8:50:44
 * @function SL
 */
public class InvitJoinGroupDetailActivity extends BaseActivity {

    private String chatid = "";
    private RoundImageView group_avatar;
    private TextView group_size_tv;
    private Button df_btn;
    private TextView join_group_amount_tv, invite_join_group, invite_sent_tv;
    private LinearLayout content_layout;
    private String contributid;
    private double myBalance, payAmount;
    private int hasPassword = 0;
    private String invitecustid;
    private View loading;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        isFullScreen = true;
        super.onCreate(savedInstanceState);
    }

    @Override
    public View bindView() {
        return null;
    }

    @Override
    public int bindLayout() {
        return R.layout.activity_invit_join_group_layout;
    }

    @Override
    public void initView(View view) {
        chatid = getIntent().getStringExtra("chatid");
        if (getIntent().hasExtra("contributid"))
            contributid = getIntent().getStringExtra("contributid");
        if (getIntent().hasExtra("invitecustid")) {
            invitecustid = getIntent().getStringExtra("invitecustid");
        }
        initView();
        initListener();
        getBalance();
        getData();
    }

    protected void initView() {
        ((TextView) findViewById(R.id.title_textview))
                .setText(R.string.invit_group);
        group_avatar = (RoundImageView) findViewById(R.id.group_avatar);
        group_avatar.SetUrl(APIConfiguration.getAvatarUrlNormal(chatid,
                PacketType.GROUP));
        group_size_tv = (TextView) findViewById(R.id.group_size_tv);
        loading = findViewById(R.id.loading);
        join_group_amount_tv = (TextView) findViewById(R.id.join_group_amount_tv);
        invite_join_group = (TextView) findViewById(R.id.invite_join_group);
        join_group_amount_tv = (TextView) findViewById(R.id.join_group_amount_tv);
        invite_sent_tv = (TextView) findViewById(R.id.invite_sent_tv);
        df_btn = (Button) findViewById(R.id.df_btn);
        content_layout = (LinearLayout) findViewById(R.id.content_layout);
    }

    protected void initListener() {
        df_btn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                if (myBalance < payAmount) {
                    showInsufficientBalanceDialog();
                } else {
                    if (hasPassword == 1) {
                        showPayPwdDialog();
                    } else {
                        showSetPwdDialog();
                    }
                }
            }
        });
    }


    private void showSetPwdDialog() {
        DialogUtility.showDialog(InvitJoinGroupDetailActivity.this,
                R.string.not_set_pay_pwd, R.string.sure, R.string.cancel, true,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(
                                InvitJoinGroupDetailActivity.this,
                                SetPayPwdActivity.class);
                        startActivity(intent);
                        finish();
                    }
                });
    }

    private void getData() {
        loading.setVisibility(View.VISIBLE);
        GroupMangerHandler groupMangerHandler = new GroupMangerHandler();
        groupMangerHandler.getGroupDetail(chatid, new GroupMangerHandler.IGetGroupDetailListener() {

            @Override
            public void onGetGroupDetailResult(GetGroupMessageDetail.GetGroupMessageDetailResult result) {
                loading.setVisibility(View.GONE);
                if (result != null) {
                    if (result.status == HttpInvokeResultCode.RESULT_OK) {
                        Message message = myHandler.obtainMessage();
                        message.obj = result.groupTalk;
                        message.what = 1;
                        myHandler.sendMessage(message);
                    } else if (result.status == HttpInvokeResultCode.GROUP_DELETED) {
                        myHandler.sendEmptyMessage(2);
                    }
                }
            }
        });

    }

    private void updateGroupInfoDialog() {
        boolean isCancelable = true;
        int contentStrResId = R.string.group_is_deleted;
        DialogUtility.showSingleBtnDialog(InvitJoinGroupDetailActivity.this,
                contentStrResId, R.string.i_got, isCancelable,
                new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        finish();
                    }
                });

    }

    private Handler myHandler = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message arg0) {
            if (arg0.what == 0) {
                if (loading != null)
                    loading.setVisibility(View.GONE);
            }
            if (arg0.what == 1) {
                GroupTalkEntity groupTalk = (GroupTalkEntity) arg0.obj;
                if (groupTalk != null) {
                    if (groupTalk.org_type_id == 3
                            && !TextUtils.isEmpty(groupTalk.group_info_json)) {
                        JSONObject json;
                        try {
                            json = new JSONObject(groupTalk.group_info_json);
                            if (json != null && json.has("amount")) {
                                String amount = json.optString("amount");
                                payAmount = Double.valueOf(amount);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    content_layout.setVisibility(View.VISIBLE);
                    group_size_tv.setText(MessageFormat.format(getResources()
                                    .getString(R.string.group_talk_memeber),
                            groupTalk.has_count));

                    if (groupTalk.creator_cust_id.equals(IMApplication
                            .getCustId())) {
                        join_group_amount_tv.setVisibility(View.GONE);
                        invite_join_group.setVisibility(View.GONE);
                        invite_sent_tv.setVisibility(View.VISIBLE);
                        df_btn.setVisibility(View.GONE);
                    } else {
                        join_group_amount_tv.setVisibility(View.VISIBLE);
                        invite_join_group.setVisibility(View.VISIBLE);
                        invite_sent_tv.setVisibility(View.GONE);
                        df_btn.setVisibility(View.VISIBLE);
                    }
                    invite_join_group.setText(MessageFormat.format(
                            getResources()
                                    .getString(R.string.invite_join_group),
                            groupTalk.creator_cust_name));
                    join_group_amount_tv.setText(MessageFormat.format(
                            getResources()
                                    .getString(R.string.join_group_amount),
                            payAmount));
                    int color = Color.argb(255, 255, 102, 0);
                    ForegroundColorSpan normalSpan = new ForegroundColorSpan(
                            color);
                    SpannableStringBuilder builder = new SpannableStringBuilder(
                            join_group_amount_tv.getText().toString());
                    builder.setSpan(normalSpan, 6, join_group_amount_tv
                                    .getText().toString().length() - 3,
                            Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    join_group_amount_tv.setText(builder);
                    if (groupTalk.join_status == 1
                            && !groupTalk.creator_cust_id.equals(IMApplication
                            .getCustId())) {
                        df_btn.setVisibility(View.GONE);
                        invite_sent_tv.setText(R.string.invited_group);
                        invite_sent_tv.setVisibility(View.VISIBLE);
                    }
                }
            } else if (arg0.what == 2) {
                updateGroupInfoDialog();
            }
            return false;
        }
    });

    /**
     * 余额不足提示
     */
    private void showInsufficientBalanceDialog() {
        loading.setVisibility(View.GONE);
        DialogUtility.showDialog(InvitJoinGroupDetailActivity.this,
                R.string.insufficient_balance, R.string.sure, R.string.cancel,
                true, new IOnBottomDialogListener() {

                    @Override
                    public void onClicked() {
                        Intent intent = new Intent(
                                InvitJoinGroupDetailActivity.this,
                                ChargeActivity.class);
                        startActivityForResult(intent, 100);
                    }
                });
    }

    private void accpetJoinGroup(String passwrod) {
        GroupMangerHandler.acceptJoinGroup(GroupType.AMOUNT_GORUP, contributid,
                1, passwrod, chatid, invitecustid, new GroupMangerHandler.IAcceptJoinGroupListener() {

                    @Override
                    public void onAcceptJoinGroupResult(int status, String msg) {
                        if (status == HttpInvokeResultCode.RESULT_OK) {
                            startChat();
                        } else if (status == 2605) {
                            showInsufficientBalanceDialog();
                        } else if (status == 2610) {
                            loading.setVisibility(View.GONE);
                            IMApplication.showToast(R.string.pay_pwd_error);
                        } else if (!TextUtils.isEmpty(msg)) {
                            loading.setVisibility(View.GONE);
                            IMApplication.showToast(msg);
                        }
                    }
                });
    }

    private void startChat() {
        Intent intent = new Intent(InvitJoinGroupDetailActivity.this,
                ChatActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        Bundle bu = new Bundle();
        SessionModel sessionModel = new SessionModel();
        sessionModel.setSessionId(Long.valueOf(chatid));
        sessionModel.setSessionType(PacketType.GROUP);
        sessionModel.setOperationType(3);
        bu.putParcelable("session", sessionModel);
        intent.putExtras(bu);
        startActivity(intent);
        finish();
    }

    /**
     * 支付密码提示框
     */
    private void showPayPwdDialog() {
        PayPwdDialog.showBottomRedDialog(InvitJoinGroupDetailActivity.this,
                new PayPwdDialog.IPayPwdInputFinishListener() {

                    @Override
                    public void onPayPwdInputFinish(String payPwd) {
                        if (!TextUtils.isEmpty(payPwd)) {
                            accpetJoinGroup(payPwd);
                        }
                    }
                });
    }

    /**
     * 获取余额
     */
    private void getBalance() {
        WalletHandle.getBalance(new WalletHandle.IGetBalanceResultListener() {

            @Override
            public void onGetBalanceResult(String balance, int status,
                                           int _haspaypassword) {
                if (status == HttpInvokeResultCode.RESULT_OK) {
                    if (!TextUtils.isEmpty(balance)) {
                        myBalance = Double.valueOf(balance);
                    }
                    hasPassword = _haspaypassword;
                }
            }
        });

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 100 && resultCode == RESULT_OK) {
            getBalance();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

}
